package org.sucri.floxs.ext.data;

import org.sucri.floxs.ext.widget.ExtWidget;
import org.sucri.floxs.utils.Json_Util;

import java.net.URL;
import java.net.URISyntaxException;
import java.net.URI;
import java.util.Map;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: Wen Yu
 * Date: Jul 19, 2007
 * Time: 12:12:31 AM
 * To change this template use File | Settings | File Templates.
 */
public class DataStore extends ExtWidget
{
  public DataStore(String var) { super(var); toRemoteSort(false); }
  public DataStore(String var, URL url)
  {
    super(var);
    try
    {
      setProxy(new HttpProxy(url.toURI().toString()));
    }
    catch (URISyntaxException e)
    {
      e.printStackTrace();
    }
    toRemoteSort(false);
    setReader(new JsonReader("test"));
  }
  public DataStore(String var, URI uri)
  {
    super(var);
    setProxy(new HttpProxy(uri.toString()));
    toRemoteSort(false);
    setReader(new JsonReader("test"));
  }
  public DataStore(String var, URI uri, JsonReader reader)
  {
    super(var);
    setProxy(new HttpProxy(uri.toString()));
    toRemoteSort(false);
    setReader(reader);
  }

  private static final String PROXY       = "proxy";
  private static final String READER      = "reader";
  private static final String REMOTE_SORT = "remoteSort";

  private HttpProxy mProxy        = null;
  private Reader    mReader       = null;
  private Boolean   mToRemoteSort = false;

  public void setProxy(  HttpProxy s) { mProxy  = s; }
  public void setReader(    Reader s) { mReader = s; }
  public void toRemoteSort(Boolean s) { mToRemoteSort = s; }

  /**
   ds = new Ext.data.Store({
   proxy: new Ext.data.HttpProxy({url: '/movie/grid_data'}),

       reader: new Ext.data.JsonReader({
           root: 'Movies',
           totalProperty: 'Total',
           id: 'id'
       }, [
           {name: 'title', mapping: 'title'},
           {name: 'plot', mapping: 'plot'},
           {name: 'release_year', mapping: 'date'},
           {name: 'genre', mapping: 'genre'},
           {name: 'mpaa', mapping: 'mpaa'},
           {name: 'directed_by', mapping: 'directed_by'}
       ]),
       // turn on remote sorting
       remoteSort: true
   });
   * 
   * @return
   */
  @Override
  public String construct()
  {
    Map<String , Object> props = new HashMap<String, Object>();
    props.put(PROXY,       mProxy);
    props.put(READER,      mReader);
    props.put(REMOTE_SORT, mToRemoteSort);

    return Json_Util.newJs("Ext.data.Store", Json_Util.toJSONString(props));
  }
  @Override
  public String render()
  {
    return "var " + getVarName() + " = " + construct();
  }
}
